define(["app",
        "resources/OrgResource",
        "services/MessageBox",
        "controllers/user/UserDetailController",
        "services/TipsService",
        "resources/UserExResource",
        "directives/common/OrgTreeView"
],  function(app) {
	
	 var deps = ["$scope","$modal","OrgResource","UserExResource","MessageBox","TipsService","$stateParams"];
	 
	 function userController($scope, $modal,OrgResource, UserExResource,MessageBox,TipsService,$stateParams) {
		init($scope);			

        $scope.treeParam = {orgType:$stateParams.orgType};
        //取全部的组织
        OrgResource.getOrgList().success(function(resp){
        	$scope.allOrgList = resp;
        });
        
		// 请求：所有用户
		$scope.getAllusers = function() {
			UserExResource.getAllusers().success(function(resp) {			
				$scope.users = resp;				
			});
		};
		
		//监控enter输入键触发搜索
        $scope.enterSearch = function($event){
            if ($event.keyCode === 13) {
                $scope.searchUser();
            }
        };
        
        $scope.searchUser = function(){
        	$scope.currentPage = 1;
        	$scope.selectedUserList = {};
            $scope.isSelectAll = false;
            
        	$scope.getUserList();
        };
        
		// 请求：按组织取用户
		$scope.getUserList = function() {
			UserExResource.getUsersByOrgAndChild($scope.selectedOrg.orgId, $scope.searchObj.searchKey, $scope.currentPage, $scope.pageSize).success(function(resp) {
				if (resp) {
					$scope.users = resp.content;
                    $scope.initTotalPages(resp.total);
				}				
			});
		};
		
		// 删除用户集提交到后台
		$scope.deleteUsers = function(userIds) {
			UserExResource.deleteUser(userIds).success(function(resp) {				
				if (resp) {					
					// 置空
					$scope.selectedUserList = {};
					// 刷新					
					$scope.getUserList();
				} else {
					alert("操作失败！");
				}
			});
		};
		
		// 将指定用户放在集合，然后提交到后台
		$scope.deleteUser = function() {
			var userArray = convertMapToArray($scope.selectedUserList);
			if (!userArray.length) {
				alert("请选择至少一个用户");
				return;
			} else {
				var userIds = [];
				for (var i = 0; i < userArray.length; i++) {
					userIds.push(userArray[i].userId);
				}
				$scope.deleteUsers(userIds);
			}
		};

        //停用/启用用户
        $scope.resetUserState = function(state) {
			var userArray = convertMapToArray($scope.selectedUserList);
			if (!userArray.length) {
				alert("请选择至少一个用户");
				return;
			}
		    var userIds = [];
			for (var i = 0; i < userArray.length; i++) {
				userIds.push(userArray[i].userId);
			}

            UserExResource.resetUserState(userIds,state).success(function(resp) {
                if (resp) {
                    // 置空
                    $scope.selectedUserList = {};
                    $scope.isSelectAll = false;
                    // 刷新
                    $scope.getUserList();

                    TipsService.show(state==1?'启用成功!':'已停用!');
                } else {
                    alert("操作失败！");
                }
            });
		};

		//停用/启用用户
        $scope.resetUserPassword = function() {
			var userArray = convertMapToArray($scope.selectedUserList);
			if (!userArray.length) {
				alert("请选择至少一个用户");
				return;
			}
		    var userIds = [];
			for (var i = 0; i < userArray.length; i++) {
				userIds.push(userArray[i].userId);
			}

            UserExResource.resetUserPassword(userIds).success(function(resp) {
                if (resp) {
                    // 置空
                    $scope.selectedUserList = {};
                    $scope.isSelectAll = false;
                    // 刷新
                    $scope.getUserList();

                    TipsService.show(resp?'重置成功!密码为:1a2b3c4d':'重置失败!');
                } else {
                    alert("操作失败！");
                }
            });
		};


		// 选择一个用户
		$scope.toggleUser = function(user) {
			$scope.selectedUser = user;
			if($scope.selectedUserList[user.userId]) {
				delete $scope.selectedUserList[user.userId];
			} else {
				$scope.selectedUserList[user.userId] = user;
			}
		};
		
		// 选择所有用户
		$scope.toggleAll = function() {
			if ($scope.isSelectAll) {
				$scope.selectedUserList = {};
				$scope.isSelectAll = false;
			} else {
				for (var i = 0; i < $scope.users.length; i++) {
					$scope.selectedUserList[$scope.users[i].userId] = $scope.users[i];
				}
				$scope.isSelectAll = true;
			}
		};
		
		// 组织节点点击事件.
		$scope.orgClick = function() {
			//1.切换当前页
            $scope.currentPage = 1;
            $scope.searchObj.searchKey = ""; //
			//2.重新加载表格
			$scope.getUserList();
			//3.置空选中项
			$scope.selectedUserList = {};
			$scope.isSelectAll = false;
		};


		// 打开编辑页面
		$scope.editUser = function(user) {
			var modalInstance = $modal.open({
				templateUrl: 'views/user/AddUser.html',
				controller: "UserDetailController",
			    resolve: {
			    	selectedOrg: function () {
			    		return $scope.selectedOrg;
				    },
				    orgList: function() {
				    	return $scope.allOrgList;
				    },
				    selectedUser: function() {
				    	return angular.copy(user || {});
				    },
				    orgType:function(){
				    	return $stateParams.orgType;
				    }
			    },
			    windowClass : "show"
			});
			
			// 回调,刷新list画面
			modalInstance.result.then(function(resp) {
				//alert(JSON.stringify(resp));				
				$scope.getUserList();
				
			}, function() {
			});
		};

         /**
          * 分页相关
          * @type {Array}
          */

         $scope.gotoPage = function(page){
             $scope.currentPage = page;
             $scope.getUserList();
         };

         $scope.nextPage = function(){
             $scope.currentPage++;
             $scope.getUserList();
         };

         $scope.upPage = function(){
             $scope.currentPage--;
             $scope.getUserList();
         };

         //初始化页数
         $scope.initTotalPages = function(count){
             if(count){
                 if(count % $scope.pageSize ==0){
                     $scope.totalPages = Math.floor(count / $scope.pageSize);
                 }else{
                     $scope.totalPages = Math.floor(count / $scope.pageSize) + 1;
                 }
                 $scope.pages = [];
                 for(var i=1;i<=$scope.totalPages;i++){
                     $scope.pages.push(i);
                 }
             }
         };

		//
	 }	//end userController
		
		
	 //用户控制初始化
	 function init($scope) {
		$scope.totalItems = 10; // 某组织下用户数量
		$scope.maxSize = 8;
		$scope.selectedUser = {}; // 点击后保存的单个用户
		$scope.selectedUserList = {}; // 点击后保存的用户列表
		$scope.isSelectAll = false;

		$scope.searchObj = {};
		$scope.searchObj.searchKey = ""; //
		
         //初始化页面
        $scope.currentPage = 1;
         /**用于展示每个页数**/
        $scope.pages = [];
        $scope.pageSize = 10;
	 }
	 
	/**
	 * 对象转列表 .
	 */
	function convertMapToArray(map) {
		var array = [];
		for(var i in map) {
			array.push(map[i]);
		}
		return array;
	}

	userController.$inject = deps;
    return app.lazy.controller("UserListController", userController);
});
